5. Basic Set Operations¶
Note
The below information is extensively based in information taken from the PowerShell® Notes for Professionals book. I plan to extend this information based on my day to day usage of the language.
A set is a collection of items which can be anything. Whatever operator we need to work on these sets are in short
the set operators and the operation is also known as set operation. Basic set operation includes Union, Interas well as addition, subtraction, etc.
5.1: Filtering: Where-Object / where /?¶
Filter an enumeration by using a conditional expression
Synonyms:
1 2 3 | Where-Object where ? |
Example:
1 | $names = @( "Aaron", "Albert", "Alphonse","Bernie", "Charlie", "Danny", "Ernie", "Frank") |
1 2 3 | $names | Where-Object { $_ -like "A*" } $names | where { $_ -like "A*" } $names |? { $_ -like "A*" } |
Returns:
1 2 3 | Aaron Albert Alphonse |
5.2: Ordering: Sort-Object / sort¶
Sort an enumeration in either ascending or descending order
Synonyms:
1 2 | Sort-Object sort |
Assuming:
1 | $names = @( "Aaron", "Aaron", "Bernie", "Charlie", "Danny" ) |
Ascending sort is the default:
1 2 | $names | Sort-Object $names | sort |
1 2 3 4 5 | Aaron Aaron Bernie Charlie Danny |
To request descending order:
1 2 | $names | Sort-Object -Descending $names | sort -Descending |
1 2 3 4 5 | Danny Charlie Bernie Aaron Aaron |
You can sort using an expression.
1 | $names | Sort-Object { $_.length } |
1 2 3 4 5 | Aaron Aaron Danny Bernie Charlie |
5.3: Grouping: Group-Object / group¶
You can group an enumeration based on an expression.
Synonyms:
1 2 | Group-Object group |
Examples:
1 | $names = @( "Aaron", "Albert", "Alphonse","Bernie", "Charlie", "Danny", "Ernie", "Frank") |
1 2 | $names | Group-Object -Property Length $names | group -Property Length |
Response:
1 2 3 4 5 | CountName Group 4 5 {Aaron, Danny, Ernie, Frank} 2 6 {Albert, Bernie} 1 8 {Alphonse} 1 7 {Charlie} |
5.4: Projecting: Select-Object / select¶
Projecting an enumeration allows you to extract specific members of each object, to extract all the details, or to compute values for each object
Synonyms:
1 2 | Select-Object SELECT |
Selecting a subset of the properties:
1 | $dir = dir "C:\MyFolder" |
1 2 3 4 5 6 | $dir | Select-Object Name, FullName, Attributes $dir | select Name, FullName, Attributes Name FullName Attributes Images C:\MyFolder\Images Directory data.txtC:\MyFolder\data.txtArchive source.cC:\MyFolder\source.cArchive |
Selecting the first element, and show all its properties:
1 | $d | select -first 1 * |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | PSPath PSParentPath PSChildName PSDrive PSProvider PSIsContainer BaseName Mode Name Parent Exists Root FullName Extension CreationTime CreationTimeUtc LastAccessTime LastAccessTimeUtc LastWriteTime LastWriteTimeUtc Attributes |